package com.qf.smsplatform.strategy.strategy.Impl;

import com.qf.smsplatform.common.constants.CacheConstants;
import com.qf.smsplatform.common.constants.StrategyConstants;
import com.qf.smsplatform.common.model.StandardSubmit;
import com.qf.smsplatform.strategy.client.CacheClient;
import com.qf.smsplatform.strategy.strategy.Strategy;
import com.qf.smsplatform.strategy.util.PushErrorMessageUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * projectName: smsplatform
 *
 * @author: MaTianWei
 * time: 2021/8/12 20:53
 * description:扣费策略
 */
@Service(value = "fee")
@Slf4j
public class FeeStrategyImpl implements Strategy {

    @Autowired
     private CacheClient cacheClient;
    @Override
    public boolean execute(StandardSubmit submit) {
        log.info("[策略模块-扣费策略] =====开始执行=====");
        int clientID = submit.getClientID();
        //1查询当前短信需要的费用
        long fee = submit.getFee();
        //2直接调用CacheClient的hincr命令,获得到扣除费用后的剩余金额
        Long remainFee = cacheClient.hincr(CacheConstants.CACHE_PREFIX_CLIENT + clientID,"fee",-fee);
        //3判断剩余金额是否小于0,证明用户剩余金额不足
        if (remainFee < 0){
            //4把之前扣除的费用加回去
            cacheClient.hincr(CacheConstants.CACHE_PREFIX_CLIENT + clientID,"fee",fee);
            //5发送消息,返回false
            PushErrorMessageUtil.sendLog(submit, StrategyConstants.STRATEGY_ERROR_FEE);
            PushErrorMessageUtil.sendReport(submit, StrategyConstants.STRATEGY_ERROR_FEE);
            log.info("[策略模块-扣费策略]  执行失败~~~~~~~~~~~~~~~~~~");
            return false;
        }
        //策略模块无法确定短信发送是否成功,到了网关 模块才能确定是否发送成功
        //TODO 再网关模块中,如果短信发送成功,扣除数据库中用户剩余的金额

        //TODO 在网关模块中,确认短信发送失败,将费用加回到redis中

        log.info("[策略模块-扣费策略] =====执行成功=====");
        return true;
    }
}
